package com.stylefeng.guns.rest.modular.wz.api.v1;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.constant.WzConsts;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.common.util.WeinXinUtil;
import com.stylefeng.guns.rest.config.properties.JwtProperties;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnPfFile;
import com.stylefeng.guns.rest.enums.EnWzAdv;
import com.stylefeng.guns.rest.enums.EnWzPrize;
import com.stylefeng.guns.rest.enums.EnWzUserSms;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.service.impl.PfFileServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzCommonServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserInfoServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.TokenUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 通用类
 */
@RestController
@RequestMapping("/wz/api/v1/common/")
public class WzCommonApi extends ApiBaseController {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzUserMapper wzUserMapper;
    @Autowired
    private WzUserSmsMapper wzUserSmsMapper;
    @Autowired
    private WzCommonServiceImpl wzCommonService;
    @Autowired
    private WzUserInfoServiceImpl userInfoService;
    @Autowired
    private WzUserOauthMapper wzUserOauthMapper;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private WzUserRecommendMapper wzUserRecommendMapper;
    @Autowired
    private WzConsts wzConsts;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzUserInfoMapper userInfoMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private WzSysMapper sysMapper;
    @Autowired
    private WzQuestionnaireMapper questionnaireMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PfOpenCityMapper openCityMapper;
    @Autowired
    private PfFileMapper pfFileMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private PfSysFileMapper sysFileMapper;
    @Autowired
    private PfFileServiceImpl fileService;
    @Autowired
    private WzUserSmsMapper userSmsMapper;

    public static String count = "";
    public static Long start = 0L;


    /**
     * 安卓apk下载
     */
    @RequestMapping("androidDownload")
    public void androidDownload(HttpServletResponse response) throws Exception{
        List<PfSysFile> sysFiles = sysFileMapper.selectList(new EntityWrapper<PfSysFile>().eq("type",EnPfFile.Type_androidDowload.getIndex()).eq("status", EnPfFile.File_Status_Used.getIndex()));
        response.sendRedirect(sysFiles.get(0).getFileUrl());
//        response.sendRedirect("/download/apk.apk");
    }

    /**
     * 安卓更新信息
     */
    @RequestMapping("androidUpdateInfo")
    public Res androidUpdateInfo(){
        Map<String,Object> res = cacheService.androidUpdateInfo("androidUpdateInfo");
        return Res.success(res);
    }



    /**
     * 系统信息 缓存
     */
    @PostMapping("wz.sys")
    public Res sys(){
        Map<String,Object> res = cacheService.commomSys("commomSys");
        return Res.success(res);
    }

    /**
     * 系统文件 缓存
     */
    @PostMapping("wzSysFile")
    public Res wzSysFile(@RequestBody ParamMap params){
        int type = params.getIntMisValid("type");
        List<WzSys> wzSys = sysMapper.selectList(new EntityWrapper<WzSys>());
        String iosVersion = params.getStr("iosVersion");
        List<Map<String,Object>> res = cacheService.wzSysFile(type);
        if(res.size() > 0){
            if(wzSys.get(0).getIosStatus() == 0 && wzSys.get(0).getIosCheckVersion().equals(iosVersion) && type == 1){
                Map<String,Object> map = new HashMap<>();
                map.put("content","");
                map.put("type","1");
                map.put("status","1");
                return Res.success(map);
            }
            return Res.success(res.get(0));
        }
           return Res.fail(res);
    }


    /**
     * 刷新token
     */
    @PostMapping("refreshToken")
    public Res refreshToken(@RequestBody ParamMap params){
        //参数校验
        String refreshToken = params.getStrMisValid("refreshToken");
        boolean r = jwtTokenUtil.isTokenExpired(refreshToken);
        if(r){
            return Res.fail(BizExceptionEnum.FRESH_TOKEN_EXPIRED);
        }else{
            String name = jwtTokenUtil.getUsernameFromToken(refreshToken);
            Map map = tokenUtil.getToken(Long.parseLong(name));
            return Res.success(map);
        }
    }

    /**
     * 登录
     */
    @PostMapping("accountLogin")
    public Res accountLogin(@RequestBody ParamMap params){
        //参数校验
        String account = params.getStrMisValid("account");
        String password = params.getStrMisValid("password");
        String loginInfo = params.getStrMisValid("loginInfo");
        //查询用户
        List<WzUser> userList = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("account", account).eq("password", password));
        if(userList.size() > 0){
            userList.get(0).setLoginInfo(loginInfo);
            userList.get(0).setUpdateTime(new Date());
            if(!StringUtils.isBlankStr(params.getStr("mobileVersion"))){
                userList.get(0).setMobileVersion(params.getStrValid("mobileVersion"));
            }
            if(!StringUtils.isBlankStr(params.getStr("iosVersion"))){
                userList.get(0).setMobileVersion(params.getStr("iosVersion"));
            }
            if(!StringUtils.isBlankStr(params.getStr("mobileType"))){
                userList.get(0).setMobileType(params.getInt("mobileType"));
            }
            int r = wzUserMapper.updateById(userList.get(0));
            if(r > 0){
                Map map = tokenUtil.getToken(userList.get(0).getUserCode());
                return Res.success(map);
            }
        }else{
            List<SysUser> sysUsers = sysUserMapper.selectList(new EntityWrapper<SysUser>().eq("account", account).eq("app_psw", password));
            if(sysUsers.size() > 0){
                Map map = tokenUtil.getToken(sysUsers.get(0).getId().longValue());
                return Res.success(map);
            }
            return Res.fail("账号或密码错误!");
        }
        return Res.fail();
    }

    /**
     * 获取手机短信
     * type:1-注册短信,2-忘记密码短信
     */
    @PostMapping("sms")
    public Res sms(@RequestBody ParamMap params) throws Exception{
        //参数校验
        String tel = params.getStrMisValid("tel");
        int type = Integer.parseInt(params.getStrMisValid("type"));
         String androidVersion = params.getStrValid("androidVersion");
        String iosVersion = params.getStrValid("iosVersion");
        String mobileType = params.getStrValid("mobileType");

        if(null==tel || "".equalsIgnoreCase(tel))
        {
            return Res.fail("手机格式错误!");
        }else{
            if(tel.length()!=11)
            {
                return Res.fail("手机格式错误!");
            }
            String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9])|(16[6]))\\d{8}$";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(tel);
            boolean isMatch = m.matches();
            if (!isMatch) {
                return Res.fail("手机格式错误!");
            }
        }
        //是否开放注册
//        if(type == EnWzUserSms.TYPE_VERIFICATION_REG.getIndex()){
//            return Res.fail("暂时只支持微信注册!");
//        }
        //查询用户
        List<WzUser> userList = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("account",tel));
//        if(type == EnWzUserSms.TYPE_VERIFICATION_REG.getIndex()){
//            String uuid = params.getStr("uuid");
            //手机注册账号数量判断
//            int c = userFixedInfoMapper.selectCount(new EntityWrapper<WzUserFixedInfo>().eq("uuid",uuid));
//            if(c >= Integer.parseInt(Consts.acountLimit)){
//                return Res.fail("该手机已经注册账号，请登录!");
//            }
//        }
        Date start = DateUtil.toDate(DateUtil.toString(new Date()) + " 00:00:00");
        Date end = DateUtil.nextDay(start);
        int r = userSmsMapper.selectCount(new EntityWrapper<WzUserSms>().like("tel",tel).between("start_time", start, end));
        if(r > 3){
            return Res.fail("请求频繁!");
        }
        if(type == EnWzUserSms.TYPE_VERIFICATION_REG.getIndex()){//1-注册验证码
            if(userList.size() > 0 && !StringUtils.isBlankStr(userList.get(0).getPassword())){
                return Res.fail("手机号已存在,请登录!");
            }
            //发送短信
            return wzCommonService.sendSms(type,tel,Consts.TEMPLATE_CODE,EnWzUserSms.SMS_TYPE_VERIFICATION_CODE.getIndex());
        }else if(type == EnWzUserSms.TYPE_VERIFICATION_OAUTH.getIndex()){//2-三方登录验证码
            if(userList.size() > 0){
                //用户
                List<WzUserOauth> userOauths = wzUserOauthMapper.selectList(new EntityWrapper<WzUserOauth>().eq("user_code",userList.get(0).getUserCode()).eq("status",1));
                if(userOauths.size() > 0){
                    if(StringUtils.isNotBlank(userOauths.get(0).getOpenid())){
                        return Res.fail("该手机号已经绑定微信!");
                    }
                }
            }
            //发送短信
            return wzCommonService.sendSms(type,tel,Consts.TEMPLATE_CODE,EnWzUserSms.SMS_TYPE_VERIFICATION_CODE.getIndex());
        }else if(type == EnWzUserSms.TYPE_VERIFICATION_FORGET_PSW.getIndex()){//3-忘记密码验证码
            if(userList.size() <= 0){
                return Res.fail("该用户不存在,请先注册!");
            }
            //发送短信
            return wzCommonService.sendSms(type,tel,Consts.TEMPLATE_CODE,EnWzUserSms.SMS_TYPE_VERIFICATION_CODE.getIndex());
        }else if(type == EnWzUserSms.TYPE_VERIFICATION_UPDATE_PSW.getIndex()){//4-修改密码验证码
            if(userList.size() <= 0){
                return Res.fail("该用户不存在,请先注册!");
            }
            //发送短信
            return wzCommonService.sendSms(type,tel,Consts.TEMPLATE_CODE,EnWzUserSms.SMS_TYPE_VERIFICATION_CODE.getIndex());
        }else if(type == EnWzUserSms.TYPE_VERIFICATION_BIND_OLDACCOUNT.getIndex()){//5-解绑手机验证码
            //发送短信
            return wzCommonService.sendSms(type,tel,Consts.TEMPLATE_CODE,EnWzUserSms.SMS_TYPE_VERIFICATION_CODE.getIndex());
        }else if(type == EnWzUserSms.TYPE_VERIFICATION_BIND_NEWACCOUNT.getIndex()){//6-绑定新手机验证码
            if(userList.size() > 0){
                return Res.fail("该手机号已绑定!");
            }
            //发送短信
            return wzCommonService.sendSms(type,tel,Consts.TEMPLATE_CODE,EnWzUserSms.SMS_TYPE_VERIFICATION_CODE.getIndex());
        }else{
            return Res.fail("不支持该类型短信！");
        }
    }

    /**
     * 账号密码注册
     */
    @Transactional
    @PostMapping("regCheck")
    public Res regCheck(@RequestBody ParamMap params){
        String vaildCode = params.getStrMisValid("vaildCode");//验证码
        String account = params.getStrMisValid("account");//手机号
        String password = params.getStrMisValid("password");
        String loginInfo = params.getStrMisValid("loginInfo");
        //查询用户
        List<WzUser> userList = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("account",account));
        if(userList.size() > 0 && !StringUtils.isBlankStr(userList.get(0).getPassword())){//已经注册
            return Res.fail("用户已存在!");
        }
        //查询验证码
        EntityWrapper<WzUserSms> ew = new EntityWrapper<>();
        ew.eq("tel",account).eq("type",EnWzUserSms.TYPE_VERIFICATION_REG.getIndex()).eq("vaild_code",vaildCode).eq("status",EnWzUserSms.STATUS_AVAILABLE.getIndex());
        List<WzUserSms> wzUserSmsList = wzUserSmsMapper.selectList(ew);
        if(wzUserSmsList.size() > 0){
            for(WzUserSms s :wzUserSmsList){
                if(!new Date().before(s.getEndTime())){
                    return Res.fail("验证码已失效!");
                }
            }
            if(userList.size() > 0 && StringUtils.isBlankStr(userList.get(0).getPassword())){//已经三方注册
                //获取token
                Map<String,String> map = tokenUtil.getToken(userList.get(0).getUserCode());
                boolean r = userInfoService.updateUser(userList.get(0),wzUserSmsList,params);
                if(r){
                    return Res.success(map);
                }
            }
            //新建用户
            Long userCode = IdWorker.getId();//用户编号
            Map map = tokenUtil.getToken(userCode);
            WzUser wzUser = new WzUser();
            wzUser.setCreateTime(new Date());
            wzUser.setUserCode(userCode);
            String invitationCode  = account.substring(8,11)+userCode.toString().substring(15,18);
            //邀请码用户
            List<WzUser> userFixedInfos = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("invitation_code",invitationCode));
            if(userFixedInfos.size() > 0){
                invitationCode = invitationCode + IDUtil.random(1);
                List<WzUser> userFixedInfos1 = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("invitation_code",invitationCode));
                if(userFixedInfos1.size() > 0){
                    invitationCode = invitationCode + IDUtil.random(1);
                }
            }
            wzUser.setInvitationCode(invitationCode);
            wzUser.setNickName("wz_"+ invitationCode);
            boolean r = userInfoService.addUser(wzUser,params,map,wzUserSmsList,invitationCode);
            if(r){
                return Res.success(map);
            }
        }else{
            return Res.fail("验证码错误!");
        }
        return Res.fail();
    }

    /**
     * 忘记密码
     */
    @PostMapping("forgetPswCheck")
    public Res forgetPswCheck(@RequestBody ParamMap params){
        String account = params.getStrMisValid("account");
        String password = params.getStrMisValid("password");
        String vaildCode = params.getStrMisValid("vaildCode");
        //查询验证码
        EntityWrapper<WzUserSms> ew = new EntityWrapper<>();
        ew.eq("tel",account).eq("type",EnWzUserSms.TYPE_VERIFICATION_FORGET_PSW.getIndex()).eq("vaild_code",vaildCode).eq("status",EnWzUserSms.STATUS_AVAILABLE.getIndex());
        List<WzUserSms> wzUserSmsList = wzUserSmsMapper.selectList(ew);
        if(wzUserSmsList.size() > 0) {
            for (WzUserSms s : wzUserSmsList) {
                if (!new Date().before(s.getEndTime())) {
                    return Res.fail("验证码已失效!");
                }
            }
            //查询用户
            List<WzUser> wzUserList = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("account",account));
            if(wzUserList.size() <= 0){
                return Res.fail("账号不存在!");
            }
            //修改密码并更新
            wzUserList.get(0).setPassword(password);
            boolean r = userInfoService.forgetPswCheck(wzUserList.get(0),wzUserSmsList);
            if(r){
                return Res.success();
            }
        }else{
            return Res.fail("验证码错误!");
        }
        return Res.fail();
    }


    /**
     * 三方登录注册
     */
    @PostMapping("oauthLogin")
    public Res oauthLogin(@RequestBody ParamMap params){
        //参数校验
        String openid = params.getStrMisValid("openid");//openid
        String nickName = params.getStrValid("nickName");
        nickName = WeinXinUtil.emojiFilter(nickName);
        params.set("nickName",nickName);
        String gender = params.getStrValid("gender");
        String avatarUrl = params.getStrValid("avatarUrl");
        String loginInfo = params.getStrMisValid("loginInfo");
        List<WzUserOauth> oauthList = wzUserOauthMapper.selectList(new EntityWrapper<WzUserOauth>().eq("openid",openid).isNotNull("user_code"));
        if(oauthList.size() > 0){//已经注册过
            WzUser user = cacheService.user(oauthList.get(0).getUserCode());
            user.setLoginInfo(loginInfo);
            if(!StringUtils.isBlankStr(params.getStr("mobileVersion"))){
                user.setMobileVersion(params.getStrValid("mobileVersion"));
            }
            if(!StringUtils.isBlankStr(params.getStr("iosVersion"))){
                user.setMobileVersion(params.getStr("iosVersion"));
            }
            if(!StringUtils.isBlankStr(params.getStr("mobileType"))){
                user.setMobileType(params.getInt("mobileType"));
            }
            userMapper.updateById(user);
            //生成token
            Map map = tokenUtil.getToken(oauthList.get(0).getUserCode());
            map.put("firstReg",0);
            return Res.success(map);
        }else{//第一次登录
            String vaildCode = params.getStr("vaildCode");//验证码
            String account = params.getStr("account");//手机号
            if(StringUtils.isBlankStr(vaildCode)){
                return Res.fail(BizExceptionEnum.FIRST_ISV_MISSING.getCode(),BizExceptionEnum.FIRST_ISV_MISSING.getMsg());
            }
            if(StringUtils.isBlankStr(account)){
                return Res.fail(BizExceptionEnum.FIRST_ISV_MISSING.getCode(),BizExceptionEnum.FIRST_ISV_MISSING.getMsg());
            }
            //查询验证码
            EntityWrapper<WzUserSms> ew = new EntityWrapper<>();
            ew.eq("tel",account).eq("type",EnWzUserSms.TYPE_VERIFICATION_OAUTH.getIndex()).eq("vaild_code",vaildCode).eq("status",EnWzUserSms.STATUS_AVAILABLE.getIndex());
            List<WzUserSms> wzUserSmsList = wzUserSmsMapper.selectList(ew);
            if(wzUserSmsList.size() > 0) {
                for (WzUserSms s : wzUserSmsList) {
                    if (!new Date().before(s.getEndTime())) {
                        return Res.fail("验证码已失效!");
                    }
                }
                EntityWrapper<WzUser> eu = new EntityWrapper<WzUser>();
                List<WzUser> userList = wzUserMapper.selectList(eu.where("account="+account+""));
                if(userList.size() > 0){//用户注册过
                    userList.get(0).setLoginInfo(loginInfo);
                    if(StringUtils.isBlankStr(userList.get(0).getAvatarUrl())){
                        userList.get(0).setAvatarUrl(avatarUrl);
                    }
                    if(StringUtils.isBlankStr(userList.get(0).getNickName())){
                        userList.get(0).setNickName(nickName);
                    }
                    if(userList.get(0).getGender().equals(0)){
                        userList.get(0).setGender(Integer.parseInt(gender));
                    }
                    boolean r = userInfoService.oauthUpdateUser(userList.get(0),params,wzUserSmsList);
                    if(r){
                        //生成token
                        Map map = tokenUtil.getToken(userList.get(0).getUserCode());
                        map.put("firstReg",0);
                        return Res.success(map);
                    }
                }else{//用户没注册过
                    //新建用户
                    Long userCode = IdWorker.getId();//用户编号
                    WzUser wzUser = new WzUser();
                    wzUser.setUserCode(userCode);
                    wzUser.setLoginInfo(loginInfo);
                    //生成token
                    Map map = tokenUtil.getToken(userCode);
                    boolean r = userInfoService.oauthSaveUser(wzUser,params,wzUserSmsList);
                    if(r){
                        map.put("firstReg",1);
                        return Res.success(map);
                    }
                }
            }else{
                return Res.fail("验证码错误!");
            }

        }

        return Res.success();
    }

    /**
     * 输入邀请码
     */
    @PostMapping("recommendCode")
    public Res recommendCode(@RequestBody ParamMap params) throws Exception{
        String invitationCode = params.getStrMisValid("invitationCode");//邀请码
        String adCode = params.getStrMisValid("adCode");//城市编号
        //城市筛选
        int openCities = openCityMapper.selectCount(new EntityWrapper<PfOpenCity>().eq("ad_code",adCode));
        if(openCities <= 0){
            return Res.fail(BizExceptionEnum.CITY_NOT_OPEN);
        }
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        //邀请码的用户
        List<WzUser> invitationUser = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("invitation_code",invitationCode));
        if(invitationUser.size() > 0){
            //判断此人邀请码是否已使用
            int m = wzUserRecommendMapper.selectCount(new EntityWrapper<WzUserRecommend>().eq("applicant_user_code",userCode));
            if(m > 0){
                return Res.fail("不能重复输邀请码!");
            }
            if(userCode.toString().equals(invitationUser.get(0).getUserCode().toString())){
                return Res.fail("不能自己邀请自己!");
            }
            //判断此人邀请码是否已使用
            int f = wzUserRecommendMapper.selectCount(new EntityWrapper<WzUserRecommend>().eq("applicant_user_code",userCode).eq("accept_user_code",invitationUser.get(0).getUserCode()));
            if(f > 0){
                return Res.fail("此邀请码已被使用!");
            }
            //接受人领取赏金
            invitationUser.get(0).setRewardBalance(invitationUser.get(0).getRewardBalance() + wzConsts.getInvitationReward()*100);
            invitationUser.get(0).setProfit(invitationUser.get(0).getProfit() + wzConsts.getInvitationReward()*100);
            //保存数据
            boolean r = userInfoService.saveUserRecommend(invitationUser.get(0),userCode);
            if(r){
                return Res.success();
            }
        }else{
            return Res.fail("邀请码错误！");
        }
        return Res.fail();
    }

    /**
     * 开放广告主页
     */
    @PostMapping("openAdvIndex")
    public Res openAdvIndex(@RequestBody ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String adCode = paramMap.getStrMisValid("adCode");
        String subtype = paramMap.getStrValid("subtype");//类型
        int subtypes = 10;
        if (!StringUtils.isBlankStr(subtype)) {
            subtypes = Integer.parseInt(subtype);
        }
        String sql = "adv_id As advId,title As title,cover_url As coverUrl,has_detail As hasDetail,questionnaire_id As questionnaireId,subtype As subtype";
        List<Map<String, Object>> advs = new ArrayList<>();
        //开启定位判断
        if(subtypes == 10){
            if (StringUtils.isBlankStr(adCode) || adCode.equals("0")) {
                advs = cacheService.sysAdv(EnWzAdv.SUBTYPE_Open_Location.getIndex());
                return Res.success(paramMap.data(advs));
            }
        }
        //开放城市判断
        List<Map<String,Object>> openCity = cacheService.openCity("openCity");
        if(subtypes == 10){
            boolean r = false;
            for(Map map:openCity){
                if(map.get("adCode").equals(adCode)){
                    r = true;
                    break;
                }
            }
            if(r == false){
                advs = cacheService.sysAdv(EnWzAdv.SUBTYPE_No_Information.getIndex());
                return Res.success(paramMap.data(advs));
            }
        }
        //苹果数据
        if (subtypes == EnWzAdv.SUBTYPE_QUESTIONNAIRE.getIndex()) {//调查问卷
                advs = questionnaireMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzQuestionnaire>().setSqlSelect(sql).in("status", new Integer[]{EnWzAdv.QUESTIONNAIRE_STATUS_weiman1.getIndex(),EnWzAdv.QUESTIONNAIRE_STATUS_yiman.getIndex()}).eq("subtype", EnWzAdv.SUBTYPE_QUESTIONNAIRE.getIndex()));
        } else if (subtypes == EnWzAdv.SUBTYPE_Knowledge_Questionnaire.getIndex()) {//知识问卷
                advs = questionnaireMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzQuestionnaire>().setSqlSelect(sql).in("status", new Integer[]{EnWzAdv.QUESTIONNAIRE_STATUS_weiman1.getIndex(),EnWzAdv.QUESTIONNAIRE_STATUS_yiman.getIndex()}).eq("subtype", EnWzAdv.SUBTYPE_Knowledge_Questionnaire.getIndex()));
        }
        //用户数据
        if(subtypes == 10){
            advs = questionnaireMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzQuestionnaire>().setSqlSelect(sql)
                    .eq("screen_city", adCode).in("status", new Integer[]{EnWzAdv.QUESTIONNAIRE_STATUS_weiman1.getIndex(),EnWzAdv.QUESTIONNAIRE_STATUS_yiman.getIndex()}).eq("subtype", EnWzAdv.QUESTIONNAIRE_TYPE_Questionnaire.getIndex()).orderBy("release_time",false));
        }
        //暂无信息
        if(subtypes == 10) {
            if (advs.size() <= 0) {
                advs = cacheService.sysAdv(EnWzAdv.SUBTYPE_Data_Statistics.getIndex());
                Long date = new Date().getTime();
                Long a = date - start;
                if(StringUtils.isBlankStr(count) || a >= 60000L){
                    List<Map<String, Object>> totalProfit = userMapper.selectMaps(Condition.create().setSqlSelect("sum(profit) As totalProfit"));
                    count = totalProfit.get(0).get("totalProfit").toString();
                    start = date;
                }
                advs.get(0).put("totalProfit", count);
                advs.get(0).put("totalProfitRemark", "外赚累计发放红包金额");
            }
        }
        return Res.success(paramMap.data(advs));
    }

    /**
     * 上传文件 @RequestPart("file")
     */
    @RequestMapping("upload.file")
    public Res uploadFile(MultipartFile file,String name,Integer type,Integer appSubtype,int uploadType) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        if(file == null){
            return Res.fail("文件不能为空!");
        }
        if(StringUtils.isBlankStr(name) || type == null || appSubtype == null){
            return Res.fail("参数不能为空!");
        }
        String[] split = file.getOriginalFilename().split("\\.");//以.分割
        String filename = IDUtil.genUUID() + "." + split[1];
        boolean r = AliOssUtil.putObject(type,filename,file.getInputStream());
        PfFile pfFile = new PfFile();
        if (r) {
            pfFile.setUserCode(userCode);
            pfFile.setName(name);
            pfFile.setType(type);
            pfFile.setAppSubtype(appSubtype);
            pfFile.setBucketName(Consts.bucketName);
            pfFile.setCreateTime(new Date());
            pfFile.setFileUrl(filename);
            pfFile.setUploadType(uploadType);
            pfFile.setStatus(EnPfFile.Status_Used.getIndex());
            int b = pfFileMapper.insert(pfFile);
            if (b > 0) {
                return Res.success(filename);
            }
        }
        return Res.fail();
    }

    /**
     * 上传文件 @RequestPart("file")
     */
    @RequestMapping("uploadFileList")
    public Res uploadFileList(List<MultipartFile> files,String name,Integer type,Integer appSubtype,int uploadType,Long advId,Long oldAdvMapId) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        if(files.size() <= 0){
            if(advId == null){
                advId = IdWorker.getId();
            }else{
                pfFileMapper.delete(new EntityWrapper<PfFile>().eq("target_id",advId));
            }
            Map map = new HashMap();
            map.put("filenames","");
            map.put("advId",advId);
            return Res.success(map);
        }
        if(StringUtils.isBlankStr(name) || type == null || appSubtype == null){
            return Res.fail("参数不能为空!");
        }
        List<String> filenames = AliOssUtil.putNewsObject(files,Consts.news_bucketName);
        List<PfFile> pfFiles = new ArrayList<>();
        String targetId = "";
        if(advId == null){
            advId = IdWorker.getId();
            targetId = advId.toString();
        }
        if(oldAdvMapId != null){
            targetId = oldAdvMapId.toString();
        }
        for(String filename:filenames){
            PfFile pfFile = new PfFile();
            pfFile.setUserCode(userCode);
            pfFile.setTargetId(targetId);
            pfFile.setName(name);
            pfFile.setType(type);
            pfFile.setAppSubtype(appSubtype);
            pfFile.setBucketName(Consts.news_bucketName);
            pfFile.setCreateTime(new Date());
            pfFile.setFileUrl(filename);
            pfFile.setUploadType(uploadType);
            pfFile.setStatus(EnPfFile.Status_Used.getIndex());
            pfFiles.add(pfFile);
        }

        boolean b = fileService.insertBatch(pfFiles);
        Map map = new HashMap();
        map.put("filenames",filenames);
        map.put("advId",advId);
        if(b){
            return Res.success(map);
        }else{
            return Res.fail();
        }
    }


    /**
     * 上传多图文件
     */
    @RequestMapping("uploadFileLists")
    public Res uploadFileLists(List<MultipartFile> files,String name,Integer type,Integer appSubtype,int uploadType) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        Long targetId = IdWorker.getId();
        if(files.size() <= 0){
            Map map = new HashMap();
            map.put("filenames","");
            return Res.success(map);
        }
        if(StringUtils.isBlankStr(name) || type == null || appSubtype == null){
            return Res.fail("参数不能为空!");
        }
        List<String> filenames = AliOssUtil.putNewsObjects(files,Consts.bucketName);
        List<PfFile> pfFiles = new ArrayList<>();
        for(String filename:filenames){
            PfFile pfFile = new PfFile();
            pfFile.setUserCode(userCode);
            pfFile.setName(name);
            pfFile.setType(type);
            pfFile.setAppSubtype(appSubtype);
            pfFile.setBucketName(Consts.bucketName);
            pfFile.setCreateTime(new Date());
            pfFile.setFileUrl(filename.substring(26,filename.length()));
            pfFile.setUploadType(uploadType);
            pfFile.setStatus(EnPfFile.Status_Used.getIndex());
            pfFiles.add(pfFile);
        }
        boolean b = fileService.insertBatch(pfFiles);
        Map map = new HashMap();
        map.put("filenames",filenames);
        map.put("targetId",targetId);
        if(b){
            return Res.success(map);
        }else{
            return Res.fail();
        }
    }

}
